<?php

//输入过滤快捷方法
function I($key,$default_val='',$request='request'){
    if($request == 'get'){
        $_GET[$key] = !isset($_GET[$key]) ? $default_val : $_GET[$key];
        return $_GET[$key];
    }
    if($request == 'post'){
        $_POST[$key] = !isset($_POST[$key]) ? $default_val : $_POST[$key];
        return $_POST[$key];
    }
    if($request == 'request'){
        $_REQUEST[$key] = !isset($_REQUEST[$key]) ? $default_val : $_REQUEST[$key];
        return $_REQUEST[$key];
    }
    if($request == 'cookie'){
        $_COOKIE[$key] = !isset($_COOKIE[$key]) ? $default_val : $_COOKIE[$key];
        return $_COOKIE[$key];
    }
    if($request == 'session'){
        $_SESSION[$key] = !isset($_SESSION[$key]) ? $default_val : $_SESSION[$key];
        return $_SESSION[$key];
    }
    return '';
}

$err_msg = array(
    '000' => '非法请求',
    '001' => '不支持的消息格式',
    '101' => '参数格式不正确',
    '102' => '参数不能为空',
    '103' => '不存在',
    '110' => '登录失败',
    '120' => '请先登录!',
    '121' => '请先登录,游客不能发言',
    '122' => '发言太频繁了',
    '200' => '请求成功',

    '103'=>'上传失败!',
    '104'=>'没有上传图片权限!',
    '106'=>'您的ip已被屏蔽!',
    '107'=>'您的账号存在风险隐患，请注册新账号后重试',
    '108'=>'您的账号正在进行风险检测，请稍候',

    '1000'=>'请先登录!',
    '1001'=>'获取用户信息失败',
    '1002'=>'您的账号已被禁用!',
    '1003'=>'您已在其他端登陆!',
    '1004'=>'操作失败',
    '1005'=>'您的账号已被禁用',
    '1006'=>'您已被禁播',
    '1007'=>'聊天室关闭',

    '1010'=>'查询账户信息失败',
    '1011'=>'您的彩币余额不足',
    '1012'=>'彩币扣除失败',

);
function to_ajax($code='200', $err_msg='',$data='',$type='json'){
    //ob_start('ob_gzhandler');
    $code = str_pad($code,3,"0",STR_PAD_LEFT);
    $msg = isset($GLOBALS['err_msg'][$code]) ? $GLOBALS['err_msg'][$code] : '';
    if($err_msg != '') $msg = $err_msg;
    $rt_data = (empty($data) && !is_array($data)) ? (object)array() : (array)$data;
    $result  = array('code'=>(string)$code, 'msg'=>(string)$msg, 'data'=>$rt_data, 'debug'=>'');
    //jsonp
    //$callback = $_GET['callback'];
    //exit($callback.'('.json_encode($result).')');
    //json
    return json_encode($result);
}

//获取客户端IP
function client_ip($type = 0) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos    =   array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip     =   trim($arr[0]);
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip     =   $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}
/**
 * POST 请求
 * @param  string $url
 * @param  array $param
 * @param  boolean $headers   请求头
 * @param  boolean $post_file 是否文件上传
 * @return string content
 * @return int $return
 */
function http_post($url, $param=array(), $headers=array(), $post_file = false, $return = 1,$timeout=5)
{
    $oCurl = curl_init();
    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    if (is_string($param) || $post_file) {
        $strPOST = $param;
    } else {
        $aPOST = array();
        foreach ($param as $key => $val) {
            $aPOST[] = $key . "=" . urlencode($val);
        }
        $strPOST = join("&", $aPOST);
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, $return);
    curl_setopt($oCurl, CURLOPT_POST, true);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
    //curl_setopt($oCurl, CURLOPT_POSTFIELDS, http_build_query($param));
    curl_setopt($oCurl, CURLOPT_TIMEOUT,(int)$timeout);
//    curl_setopt($oCurl, CURLOPT_CONNECTTIMEOUT_MS,1000);
    //发送请求头
    $sendhead = array();
    foreach($headers as $k=>$v){
        $sendhead[] = $k.':'.$v;
    }
    curl_setopt($oCurl, CURLOPT_HTTPHEADER, $sendhead);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    if(curl_errno($oCurl) == CURLE_OPERATION_TIMEOUTED){
        curl_close($oCurl);
        $LogData = array(
            'url' => $url,
            'params' => $strPOST,
            'header' => $sendhead,
            'result' => 'timeout:'.$timeout."s",
        );
        writeLogNew($LogData,'timeout');
        return;
        //to_ajax('103','请求超时，请稍后再试');
    }
    curl_close($oCurl);
    if (intval($aStatus["http_code"]) == 200) {
        return $sContent;
    } else {
        return $sContent;
    }
}
function http_get($url, $headers=array(), $timeout=5, $use_https=false){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    if($use_https){
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
    }
    //发送请求头
    $sendhead = array();
    foreach($headers as $k=>$v) $sendhead[] = $k.':'.$v;
    curl_setopt($curl, CURLOPT_HTTPHEADER, $sendhead);
    //curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_TIMEOUT,(int)$timeout);
    $sContent = curl_exec($curl);
    curl_close($curl);
    return $sContent;
}
//生成随机字符串
function rand_char($length = 12,$chars = null){
    if( empty($chars) ){
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    }
    $chars = str_shuffle($chars);
    $num = $length < strlen($chars) - 1 ? $length:str_len($chars) - 1;
    return substr($chars,0,$num);
}
//生成唯一订单号
function order_no()
{
//    /* 选择一个随机的方案 */
//    mt_srand((double) microtime() * 1000000);
//    //return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
//    return date('Ymd') . uniqid();
    return date('YmdHis').rand(100000,999999);
}
//生成优惠券码
function coupon_no() {
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0,25)]
        .strtoupper(dechex(date('m')))
        .date('d').substr(time(),-5)
        .substr(microtime(),2,5)
        .sprintf('%02d',rand(0,99));
    for(
        $a = md5( $rand, true ),
        $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
        $d = '',
        $f = 0;
        $f < 8;
        $g = ord( $a[ $f ] ),
        $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
        $f++
    );
    return $d;
}
//取出二维数组一列
if(!function_exists('array_column'))
{
    function array_column($input, $columnKey, $indexKey = NULL)
    {
        $columnKeyIsNumber = (is_numeric($columnKey)) ? TRUE : FALSE;
        $indexKeyIsNull = (is_null($indexKey)) ? TRUE : FALSE;
        $indexKeyIsNumber = (is_numeric($indexKey)) ? TRUE : FALSE;
        $result = array();

        foreach ((array)$input AS $key => $row)
        {
            if ($columnKeyIsNumber)
            {
                $tmp = array_slice($row, $columnKey, 1);
                $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : NULL;
            }
            else
            {
                $tmp = isset($row[$columnKey]) ? $row[$columnKey] : NULL;
            }
            if ( ! $indexKeyIsNull)
            {
                if ($indexKeyIsNumber)
                {
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && ! empty($key)) ? current($key) : NULL;
                    $key = is_null($key) ? 0 : $key;
                }
                else
                {
                    $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
                }
            }

            $result[$key] = $tmp;
        }

        return $result;
    }
}
//删除空格
function trimall($str)
{
    $qian=array(" ","　","\t","\n","\r");$hou=array("","","","","");
    return str_replace($qian,$hou,$str);
}
//二维数组排序
function array_sort($arr, $field, $desc = false){
    $fieldArr = array();
    foreach ($arr as $k => $v) {
        $fieldArr[$k] = $v[$field];
    }
    $sort = $desc == false ? SORT_ASC : SORT_DESC;
    array_multisort($fieldArr, $sort, $arr);
    return $arr;
}

//加密
function to_encode($str, $key='20xnH9_mT', $expire=0){
    $stop_time = strtotime("+{$expire} seconds");
    $str = $str.':'.base64_encode($key).':'.$stop_time;
    $str = base64_encode($str);
    $str = strrev($str);
    return $str;
}
//解密
function to_decode($str, $key='20xnH9_mT'){
    $str = strrev($str);
    $str = base64_decode($str);
    //$str = rtrim($str,':'.base64_encode($key));
    $exp_str = explode(':', $str);
    $str     = $exp_str[0];
    return $str;
}
/**
 * 字符截取 支持UTF8/GBK
 * @param $string
 * @param $length
 * @param $dot
 */
function str_cut($string, $length, $dot = '...') {
    global $charset;
    if(strlen($string) <= $length) return $string;
    $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
    $strcut = '';
    if(strtolower($charset) == 'utf-8') {
        $n = $tn = $noc = 0;
        while($n < strlen($string)) {
            $t = ord($string[$n]);
            if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                $tn = 1; $n++; $noc++;
            } elseif(194 <= $t && $t <= 223) {
                $tn = 2; $n += 2; $noc += 2;
            } elseif(224 <= $t && $t <= 239) {
                $tn = 3; $n += 3; $noc += 2;
            } elseif(240 <= $t && $t <= 247) {
                $tn = 4; $n += 4; $noc += 2;
            } elseif(248 <= $t && $t <= 251) {
                $tn = 5; $n += 5; $noc += 2;
            } elseif($t == 252 || $t == 253) {
                $tn = 6; $n += 6; $noc += 2;
            } else {
                $n++;
            }
            if($noc >= $length) break;
        }
        if($noc > $length) $n -= $tn;
        $strcut = substr($string, 0, $n);
    } else {
        for($i = 0; $i < $length; $i++) {
            $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
        }
    }
    $strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
    return $strcut.$dot;
}

//上传单图
function upload_image($field='', $dir='', $build_thumb=false, $thumb_width='180', $thumb_height='180'){
    $image = '';
    include_once (ROOT_PATH . 'include/upload.class.php');
    $images_dir = "images/$dir/"; // 文件上传路径，结尾加斜杠
    $thumb_dir  = ''; // 缩略图路径（相对于$images_dir） 结尾加斜杠，留空则跟$images_dir相同
    if (!file_exists(ROOT_PATH . $images_dir)) mkdir(ROOT_PATH . $images_dir, 0777);
    $img = new Upload(ROOT_PATH . $images_dir, $thumb_dir); // 实例化类文件
    // 图片上传
    if ($_FILES[$field]['name'] != "") {
        //$image_name = $img->upload_image($field, $img->create_file_name($dir));
        $image_name = $img->upload_image($field);
        $image = $images_dir . $image_name;
        //生成缩略图
        if($build_thumb) $img->make_thumb($image_name, $thumb_width, $thumb_height);
    }
    return $image;
}
//上传相册
function upload_multi_image($field, $dir='', $build_thumb=false, $thumb_width='180', $thumb_height='180'){
    $image = array();
    include_once (ROOT_PATH . 'include/upload.class.php');
    $images_dir = "images/$dir/"; // 文件上传路径，结尾加斜杠
    $thumb_dir  = ''; // 缩略图路径（相对于$images_dir） 结尾加斜杠，留空则跟$images_dir相同
    $img        = new Upload(ROOT_PATH . $images_dir, $thumb_dir); // 实例化类文件
    if (!file_exists(ROOT_PATH . $images_dir)) mkdir(ROOT_PATH . $images_dir, 0777);
    // 图片上传
    //$image_names = $img->upload_multi_image($field, $img->create_file_name($dir));
    $image_names = $img->upload_multi_image($field);
    if(count($image_names) > 0){
        foreach($image_names as $k=>$v){
            $image[$k] = !empty($v) ? $images_dir.$v : $v;
            if($build_thumb && !empty($v)) $img->make_thumb($v, $thumb_width, $thumb_height);
        }
    }
    return $image;
}
//获取缩略图名称
function thumb_path($img_path=''){
    if($img_path == '') return '';
    include_once (ROOT_PATH . 'include/upload.class.php');
    $images_dir = "images/$dir/";
    $thumb_dir  = '';
    $filetype   = '';
    $img        = new Upload(ROOT_PATH . $images_dir, $thumb_dir);
    $upfile_type = explode(',', $img->upfile_type);
    foreach($upfile_type as $k=>$v){
        if(strpos($img_path, $v)) $filetype = $v;
        $img_path = str_replace('.'.$v, '', $img_path);
    }
    if($filetype == '') return '';
    $thumb_path = $img_path.'_thumb.'.$filetype;
    return $thumb_path;
}

/**
 * 读取CSV文件
 * @param string $csv_file csv文件路径
 * @param int $lines       读取行数
 * @param int $offset      起始行数
 * @return array|bool
 */
function read_csv($csv_file = '', $lines = 0, $offset = 0)
{
    if (!$fp = fopen($csv_file, 'r')) {
        return false;
    }
    $i = $j = 0;
    while (false !== ($line = fgets($fp))) {
        if ($i++ < $offset) {
            continue;
        }
        break;
    }
    $data = array();
    while (($j++ < $lines) && !feof($fp)) {
        $data[] = fgetcsv($fp);
    }
    fclose($fp);
    return $data;
}
/**
 * 导出CSV文件
 * @param array $data        数据
 * @param array $header_data 首行数据
 * @param string $file_name  文件名称
 * @return string
 */
function export_csv($data = [], $header_data = [], $file_name = '')
{
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename='.$file_name);
    header('Cache-Control: max-age=0');
    $fp = fopen('php://output', 'a');
    if (!empty($header_data)) {
        foreach ($header_data as $key => $value) {
            $header_data[$key] = iconv('utf-8', 'gbk', $value);
        }
        fputcsv($fp, $header_data);
    }
    $num = 0;
    //每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
    $limit = 100000;
    //逐行取出数据，不浪费内存
    $count = count($data);
    if ($count > 0) {
        for ($i = 0; $i < $count; $i++) {
            $num++;
            //刷新一下输出buffer，防止由于数据过多造成问题
            if ($limit == $num) {
                ob_flush();
                flush();
                $num = 0;
            }
            $row = $data[$i];
            foreach ($row as $key => $value) {
                $row[$key] = iconv('utf-8', 'gbk', $value);
            }
            fputcsv($fp, $row);
        }
    }
    fclose($fp);
}
//生成32位的消息ID
function msg_id() {
    $s = [];
    $hexDigits = "0123456789abcdef";
    for ($i = 0; $i < 36; $i++) {
        $s[$i] = substr($hexDigits, rand(0,15), 1);
    }
    $s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    $s[19] = substr(($s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    $s[8] = $s[13] = $s[18] = $s[23] = "-";
    return join("",$s);
}

//判断手机
function isMobile() {
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) return true;

    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']) && stristr($_SERVER['HTTP_VIA'], "wap")) {
        return true;
    }

    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $mobile_agents = array ('iphone','android','phone','mobile','wap','netfront','java','opera mobi',
        'opera mini','ucweb','windows ce','symbian','series','webos','sony','blackberry','dopod',
        'nokia','samsung','palmsource','xda','pieplus','meizu','midp','cldc','motorola','foma',
        'docomo','up.browser','up.link','blazer','helio','hosin','huawei','novarra','coolpad',
        'techfaith','alcatel','amoi','ktouch','nexian','ericsson','philips','sagem','wellcom',
        'bunjalloo','maui','smartphone','iemobile','spice','bird','zte-','longcos','pantech',
        'gionee','portalmmm','jig browser','hiptop','benq','haier','^lct','320x320','240x320',
        '176x220','windows phone','cect','compal','ctl','lg','nec','tcl','daxian','dbtel','eastcom',
        'konka','kejian','lenovo','mot','soutec','sgh','sed','capitel','panasonic','sonyericsson',
        'sharp','panda','zte','acer','acoon','acs-','abacho','ahong','airness','anywhereyougo.com',
        'applewebkit/525','applewebkit/532','asus','audio','au-mic','avantogo','becker','bilbo',
        'bleu','cdm-','danger','elaine','eric','etouch','fly ','fly_','fly-','go.web','goodaccess',
        'gradiente','grundig','hedy','hitachi','htc','hutchison','inno','ipad','ipaq','ipod',
        'jbrowser','kddi','kgt','kwc','lg ','lg2','lg3','lg4','lg5','lg7','lg8','lg9','lg-','lge-',
        'lge9','maemo','mercator','meridian','micromax','mini','mitsu','mmm','mmp','mobi','mot-',
        'moto','nec-','newgen','nf-browser','nintendo','nitro','nook','obigo','palm','pg-',
        'playstation','pocket','pt-','qc-','qtek','rover','sama','samu','sanyo','sch-','scooter',
        'sec-','sendo','sgh-','siemens','sie-','softbank','sprint','spv','tablet','talkabout',
        'tcl-','teleca','telit','tianyu','tim-','toshiba','tsm','utec','utstar','verykool','virgin',
        'vk-','voda','voxtel','vx','wellco','wig browser','wii','wireless','xde','pad','gt-p1000');

    $is_mobile = false;
    foreach ($mobile_agents as $device) {
        if (stristr($user_agent, $device)) {
            $is_mobile = true;
            break;
        }
    }
    return $is_mobile;
}

/**
 * 生成签名信息
 * $secretKey 产品私钥
 * $params 接口请求参数，不包括signature参数
 */
function gen_signature($secretKey,$params){
    ksort($params);
    $buff="";
    foreach($params as $key=>$value){
        $buff .=$key;
        $buff .=$value;
    }
    $buff .= $secretKey;
    return md5(mb_convert_encoding($buff, "utf8", "auto"));
}